﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Sharepoint.Client;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace SharepointCompanion
{
    public sealed partial class SharepointLoginDialog : UserControl
    {
        Popup _popup;
        TaskCompletionSource<SPConnection> _resultTask = new TaskCompletionSource<SPConnection>();

        public SharepointLoginDialog()
        {
            this.InitializeComponent();
        }

        async void  Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            await WaitForLayoutUpdateAsync(this);
            ResizeLayoutRoot();
        }

        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SPLogin c = new SPLogin(uri.Text);
                Login.IsEnabled = false;
                var connection = await c.SigninAsync(usr.Text, pwd.Password);
                if (connection!=null)
                {
                    _resultTask.SetResult(connection);
                }
                else
                {
                    usr.Background = new SolidColorBrush(Windows.UI.Colors.Red);
                    pwd.Background = new SolidColorBrush(Windows.UI.Colors.Red);
                }
            }
            catch (Exception ex)
            {
                uri.Background = new SolidColorBrush(Windows.UI.Colors.Red);
            }
            finally
            {
                Login.IsEnabled = true;
            }
        }

        public async Task<SPConnection> ShowAsync()
        {
            Window.Current.Content.KeyUp += OnGlobalKeyUp;
            Window.Current.SizeChanged += Current_SizeChanged;
            try
            {
                _popup = new Popup() { Child = this };
                _popup.IsOpen = true;
                await WaitForLayoutUpdateAsync(this);
                ResizeLayoutRoot();
                var result = await _resultTask.Task;
                _popup.IsOpen = false;

                return result;
            }
            finally
            {
                Window.Current.Content.KeyUp -= OnGlobalKeyUp;
                Window.Current.SizeChanged -= Current_SizeChanged;
            }
        }



        private FrameworkElement RootFrameworkElement
        {
            get
            {
                return (FrameworkElement)Window.Current.Content;
            }
        }

        private void ResizeLayoutRoot()
        {
            var root = RootFrameworkElement;
            _layoutRoot.Width = root.ActualWidth;
            _layoutRoot.Height = root.ActualHeight;
            _dialogRoot.Width = root.ActualWidth;
        }

        public static Task WaitForLayoutUpdateAsync(FrameworkElement frameworkElement)
        {
            TaskCompletionSource<object> b = new TaskCompletionSource<object>();

            EventHandler<object> a = null;
            a=(o, e) =>
            {
                b.SetResult(e);
                frameworkElement.LayoutUpdated -= a;    
            };

            frameworkElement.LayoutUpdated += a;
            return b.Task;
        }

        private void Cancel_Click_1(object sender, RoutedEventArgs e)
        {
            _resultTask.SetResult(null);
        }

        void OnGlobalKeyUp(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Escape)
            {
                _resultTask.SetResult(null);
                e.Handled = true;
            }
        }
        //private void OnGlobalKeyUp(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Windows.System.VirtualKey.Escape)
        //    {
        //        _resultTask.SetResult(null);
        //        e.Handled = true;
        //    }
        //}
    }
}
